const fs = require("fs");
const express = require("express");

// 加载cookie模块
const cookieParser = require("cookie-parser");
// 加载session模块
const session = require("express-session");

const app = express();
app.listen(3000, () => console.log("服务启动了"));

// 设置中间件
app.use(cookieParser());
app.use(
    session({
        secret: "abcde",
        resave: false,
        saveUninitialized: false,
    })
);

// 显示index.html
app.get("/index.html", (req, res) => {
    // 判断，isLogin是否是abc
    // cookie
    // console.log(req.cookies.isLogin); // abc
    // if (req.cookies.isLogin != "abc") {
    //     return res.send(
    //         '<script>alert("请先登录"); location.href="/login.html"</script>'
    //     );
    // }
    if (req.session.isLogin != true) {
        return res.send(
            '<script>alert("请先登录"); location.href="/login.html"</script>'
        );
    }

    fs.readFile("./public/index.html", "utf-8", (err, data) => {
        if (err) return console.log(err);
        res.send(data);
    });
});

// 显示login.html
app.get("/login.html", (req, res) => {
    fs.readFile("./public/login.html", "utf-8", (err, data) => {
        if (err) return console.log(err);
        res.send(data);
    });
});

// 完成登录的接口
app.use(express.urlencoded({ extended: false }));
app.post("/api/login", (req, res) => {
    if (req.body.username === "admin" && req.body.password === "123") {
        // res.send(req.body);
        // res.send(req.body.username);
        // 假设 账号是 admin、密码是123 表示登录成功
        // 设置cookie
        // res.cookie("isLogin", "abc", { maxAge: 1000 * 60 * 60 });
        // 设置session
        req.session.isLogin = true;

        res.send({ status: 200, msg: "登录成功" });
    } else {
        res.send({ status: 500, msg: "登录失败" });
    }
});